package org.viva.service.wx;

import java.io.InputStream;
import java.util.Collections;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.viva.core.Log;
import org.viva.util.wx.AesException;
import org.viva.util.wx.HTTPUtils;
import org.viva.util.wx.WXBizMsgCrypt;

import net.sf.json.JSONObject;


/**
 * 微信认证类
 */
public class WeiXinAuthService {
	
	public final String Access_token_URL = String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%1$s&secret=%2$s", WXBizMsgCrypt.getAppId(),  WXBizMsgCrypt.getAppSecret());
	public final String User_info_URL = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=%1$s&openid=%2$s&lang=" + Locale.getDefault();
	
	/**1 获取access token,
	 * 有效期目前为2个小时，需定时刷新，重复获取将导致上次获取的access_token失效
	 * @author LUYANFENG @ 2015年5月20日
	 */
	public String getAccess_token(){
		String text = null;
		Map<String, Object> map = HTTPUtils.getAccess_token(this.Access_token_URL);
		text = (String) map.get("access_token");
		if(StringUtils.isBlank(text)){
			text = (String) map.get("errmsg");
		}
		return text;
	}
	
	
	/**2 获取微信服务器IP地址
	 * @author LUYANFENG @ 2015年5月20日
	 */
	public boolean getCallbackip(){
		//TODO 
		return false;
	}
	
	/**3 证认
	 * @author LUYANFENG @ 2015年5月20日
	 * @param nonce 
	 * @param timestamp 
	 * @param signature 
	 * @param msg_signature 
	 * @param servletInputStream 
	 */
	public boolean checkSignature(String signature, String timestamp, String nonce,String msg_signature, InputStream servletInputStream){
		try {
			return  WXBizMsgCrypt.build(signature,timestamp ,nonce ,msg_signature, servletInputStream)
								.verifyUrl(signature, timestamp, nonce);
		} catch (AesException e) {
			e.printStackTrace();
			return false;
		}
	}
	
	public Map<String,Object> getUserInfo() {
		WXBizMsgCrypt build = WXBizMsgCrypt.getCurrentSession();
		
		try {
			Map<String, Object> respMap = build.decryptXMLMsg();
			String OpenID = respMap.get("FromUserName").toString(); // OpenID
			
			String respstr = HTTPUtils.doGet(String.format(this.User_info_URL, this.getAccess_token(), OpenID ));
			Map<String,Object> userInfoMap = JSONObject.fromObject(respstr);
//			Log.debug("反回的用户信息 : "+userInfoMap);
			if(StringUtils.isNotBlank( (String)userInfoMap.get("errmsg") )){
				userInfoMap.put("errmsg", "用户信息获取失败！"+ userInfoMap.get("errmsg"));
				return userInfoMap;
			}
			String subscribe = userInfoMap.get("subscribe").toString();
			if("0".equals(subscribe)){
				userInfoMap = new HashMap<String,Object>();
				userInfoMap.put("errmsg", "用户没有关注该公众号！");
				return userInfoMap;
			}
//			userInfoMap.forEach((key, val) -> {log.debug(String.format("%1$20s : %2$s",key , val.toString())); });
			for(Map.Entry<String, Object> m : userInfoMap.entrySet()){
				Log.debug(String.format("%1$20s : %2$s",m.getKey() , m.getValue().toString()));
			}
		
//			String subscribe_time = userInfoMap.get("subscribe_time").toString(); 
//			Object unionid = userInfoMap.get("unionid");// 公众号下唯一
			
//			Map<String, Object> sysUserMap = this.accDao.findWXUser( OpenID ,unionid ,subscribe_time);
//			if(sysUserMap == null || sysUserMap.isEmpty()){
//				boolean ok = this.accDao.addWXUser(userInfoMap);
//				if( !ok){
//					userInfoMap = new HashMap<String,Object>();
//					userInfoMap.put("errmsg", "用户还没有关联系统账号！");
//					return userInfoMap;
//				}
//				userInfoMap.put("newuser", "1");
//				Log.debug("加了用户："+userInfoMap);
//				return userInfoMap;
//			}
			return null;
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return Collections.emptyMap();
	}
	
}
